﻿/*
* C# 代碼動態編譯器 類
 * 
* 創建日期 2009-3-28
* 創建人 Skybot 
 */



using System;
using System.Collections.Generic;
using System.Linq;


namespace Tong.CreateNewType
{
    using System.Reflection;
    using System.Reflection.Emit;
    using Microsoft.CSharp;

 

    /// <summary>
    ///C#代碼動態編譯器
    ///請使用實例化後訪問
    /// </summary>
    public class CSharpExe
    {

        public CSharpExe()
        {
            MyCparmae.GenerateInMemory = true;
            MyCparmae.GenerateExecutable = false;
            MyCparmae.IncludeDebugInformation = true;
            MyCparmae.CompilerOptions = "/target:library";//create type Libray

            MyCparmae.ReferencedAssemblies.Add("System.dll");
            MyCparmae.ReferencedAssemblies.Add("System.Web.dll");
            MyCparmae.ReferencedAssemblies.Add("System.Data.dll");
            MyCparmae.ReferencedAssemblies.Add("System.Xml.dll");



        }

        /// <summary>
        /// 新建的编译器类型
        /// </summary>
        Microsoft.CSharp.CSharpCodeProvider MyCSharp = new CSharpCodeProvider();

        /// <summary>
        /// 实例化新的编写的参数
        /// </summary>
        private System.CodeDom.Compiler.CompilerParameters MyCparmae = new System.CodeDom.Compiler.CompilerParameters();


        /// <summary>
        /// 默认编译参数
        /// </summary>
        public System.CodeDom.Compiler.CompilerParameters CompilerCparmae
        {
            get { return MyCparmae; }
        }

        /// <summary>
        /// 動態編譯
        /// </summary>
        /// <param name="Code">執行的代碼</param>
        /// <param name="compilerParameters">編譯的參數</param>
        /// <returns>返回編譯後的程集</returns>
        public System.CodeDom.Compiler.CompilerResults RunCode(string[] codes, System.CodeDom.Compiler.CompilerParameters compilerParameters = null)
        {
            if (compilerParameters == null)
            {
                compilerParameters = MyCparmae;
            }


            return MyCSharp.CompileAssemblyFromSource(compilerParameters, codes);
        }

        /// <summary>
        /// 動態編譯
        /// </summary>
        /// <param name="code">執行的代碼</param>
        /// <param name="compilerParameters">編譯的參數</param>
        /// <returns>返回編譯後的程集</returns>
        public System.CodeDom.Compiler.CompilerResults RunCode(string code, System.CodeDom.Compiler.CompilerParameters compilerParameters = null)
        {
            return RunCode(new string[] { code }, compilerParameters);
        }

    }
}